<?php

namespace App\Models\Goods;
use Illuminate\Database\Eloquent\Model;

/**
 * 商品收藏模型类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Models\Goods
 */
class Favorite extends Model
{
    protected $table = 'b2c_goods_favorite';
    protected $primaryKey = 'favorite_id';
    /**
     * 商品是否已收藏
     *
     * @param int $customerId
     * @param int $goodsId
     * @return int
     */
    public static function checkIsFavorite(int $customerId, int $goodsId)
    {
        return Favorite::query()->where('customer_id', $customerId)->where('goods_id', $goodsId)->count();
    }

    /**
     * 保存收藏
     *
     * @param array $data
     * @return bool
     */
    public static function create(array $data)
    {
        $favorite = new Favorite();
        foreach ($data as $field => $value)
        {
            $favorite->{$field} = $value;
        }
        return $favorite->save();
    }

    /**
     * 取消收藏
     *
     * @param int $customerId
     * @param int $goodsId
     * @return mixed
     */
    public static function cancel(int $customerId, int $goodsId)
    {
        return Favorite::query()->where('customer_id', $customerId)->where('goods_id', $goodsId)->delete();
    }

    /**
     * 收藏列表
     *
     * @param int $customerId
     * @return
     */
    public static function getByCustomerId($customerId = 0)
    {
        $favorite = Favorite::query();
        if($customerId) {
            $favorite->where('customer_id', $customerId);
        }
        return $favorite;
    }

    /**
     * 批量取消收藏
     *
     * @param int $customerId
     * @param array $goodsId
     * @return mixed
     */
    public static function batchCancel(int $customerId, array $goodsIds)
    {
        return Favorite::query()->where('customer_id', $customerId)->whereIn('goods_id', $goodsIds)->delete();
    }

    /**
     * 获取收藏列表（中台）
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(array $filter = [])
    {
        $favorite = Favorite::query();
        if(!empty($filter['customer_name'])) {
            $favorite->where('customer_name', 'like', '%' . $filter['customer_name'] . '%');
        }
        if(!empty($filter['goods_name'])) {
            $favorite->where('goods_name', 'like', '%' . $filter['goods_name'] . '%');
        }
        return $favorite;
    }
}
